<?php
/**
 * 用户组模型
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-05-29
 * @author chenyan
 */

class groupModel extends model
{
	/**************************************************************************
	 * 返回 值说明
	 * 1.返回的数组（group）说明
	 * 	group_id	int		用户组ID
	 *  group_name 	string	用户组名
	 *  user_id    	int		创建用户ID
	 *  flag		int		加入类型		0：申请加入	1：添加加入
	 * 	user_count 	int		成员数量
	 * 
	 * 
	 * 
	 * 2.若返回值为操作是否成功	1：成功      0或则负数：失败
	 **************************************************************************/
	
	/**
	 * 添加用户组
	 * @param $group_name 用户组名
	 * @param $user_id    创建用户ID
	 * 
	 * @return		新加入用户组id
	 */
	public function create($group_name, $user_id,$flag, $users = array()) {
		$group_id = DB::insert('group', array('group_name' => $group_name, 'user_id' => $user_id, 'flag' => intval($flag),'user_count'=>1));
		//并将添加者加入该组
		DB::insert('user_group',array('user_id'=>$user_id,'group_id'=>$group_id));
		foreach($users as $item){
			if($item != $user_id){
				DB::insert('user_group',array('user_id'=>$item,'group_id'=>$group_id));
			}
		}
		return $group_id;
	}
	public function get_groups_by_user_id($user_id){
		$group_ids = DB::fetchArray('SELECT group_id FROM '.DB::table('user_group').' WHERE user_id = '.$user_id);
		$gs = array();
		foreach($group_ids as $i){
			$gs[] = $i['group_id'];
		}
		if(count($gs) == 0){
			return array();
		}
		$data = array();
		
		$groupdata = DB::fetchArray('SELECT * FROM '.DB::table('group').' WHERE group_id IN ('.implode(',', $gs).')');
		foreach($groupdata as $item){
			$data[$item['group_id']] = $item;
		}
		$users = DB::fetchArray('SELECT a.group_id, b.user_id, b.username FROM '.DB::table('user_group').' as a, '.DB::table('user').' as b WHERE group_id IN ('.implode(',', $gs).') AND a.user_id = b.user_id');
		foreach($users as $item){
			if(empty($data[$item['group_id']]['members'])){
				$data[$item['group_id']]['members'] = array();
			}
			$data[$item['group_id']]['members'][] = array('user_id' => $item['user_id'], 'username' => $item['username']);
		}
		return $data;
	}
	
	public function get_group_by_id($group_id){
		$data = DB::fetchOne('SELECT * FROM '.DB::table('group').' WHERE group_id = '.$group_id);
		$members = DB::fetchArray('SELECT user_id FROM '.DB::table('user_group').' WHERE group_id = '.$group_id);
		$data['members'] = array();
		foreach($members as $item){
			$data['members'][] = $item['user_id'];
		}
		return $data;
	}
	
	public function edit($group_id, $group_name, $members){
		$groups = $this->get_group_by_id($group_id);
		$member['add'] = array_diff($members, $groups['members']);
		$sql = 'INSERT INTO '.DB::table('user_group').' (user_id, group_id) VALUES ';
		if(count($member['add'])>0){
			$a = array();
			foreach($member['add'] as $i){
				$a[] = "({$i}, {$group_id})";
			}
			$sql .= implode(',', $a);
			DB::query($sql);
		}
		$member['del'] = array_diff($groups['members'], $members);
		if(count($member['del'])>0){
			DB::delete('user_group', 'group_id = '.$group_id.' AND user_id IN ('.implode(',', $member['del']).')');
		}
		DB::update('group', array('group_name' => $group_name), 'group_id = '.$group_id);
	}
	
	/**
	 * 删除用户组
	 * @param int $group_id 用户组ID
	 * 
	 * @return  1:成功 
	 * 			0:失败
	 * 			-1：该用户组下有用户，不能删除
	 */
	public function delete($user_id){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('user_group')." where group_id=$group_id");
		if($row['num']>0){	//保证当前用户组下无用户才能删除
			return -1;
		}
		
		$condition = "group_id=$group_id";
		$row = DB::delete('group',$condition);
		if($row>=0) return 1;
		else return 0;
	}
	
	/**
	 * 修改用户组名
	 * @param int $group_id 		用户组ID
	 * @param string $group_name	用户组名
	 * 
	 * @return  1:成功 
	 * 			0:失败
	 */
	public function set_group_name($group_id,$group_name){
		$data = array('group_name' => $group_name);
		$condition = "group_id=$group_id";
		$row = DB::update('group',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}
	

	/**
	 * 用户组成员转移
	 * @param int $src_group_id	源用户组id
	 * @param int $des_group_id 目的用户组id
	 * 
	 * @return  1:成功 
	 * 			0:失败
	 */
	public function copy_group_member($src_group_id,$des_group_id){
		$data = array('group_id' => $des_group_id);
		$condition = "group_id=$src_group_id";
		$row = DB::update('user_group',$data,$condition);
		if($row>=0) return 1;
		else return 0;
	}
	
	/**
	 * 修改用户所在组
	 * @param int $user_id		用户ID
	 * @param int $group_id		用户组ID
	 * @return  				1:成功  0:失败
	 */
	public function set_user_group($user_id,$group_id){
		$data = array('group_id' => $group_id);
		$condition = "user_id=$user_id";
		$row = DB::update('user_group',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}
	
	/**
	 * 根据用户组ID获取用户组信息
	 * @param int $group_id		用户组ID
	 * 
	 * @return 一维数组
	 */
	public function get_group_by_group_id($group_id){
		$row = DB::fetchOne("SELECT * FROM ".DB::table('group')." WHERE group_id = ".DB::escape_string($group_id));
		if(count($row) == 0){
			return array();
		}
		return $row;
	}
	
	/**
	 * 分页获取用户租列表
	 * @param int $pagesize 每页大小
	 * @param int $pagenum  页号
	 * 
	 * @return 二维数组
	 */
	public function get_groups($pagesize,$pagenum){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('group'));
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$r = DB::fetchArray("SELECT * FROM ".DB::table('group')." limit $limitstart,$pagesize");
		return $r;
	}
	
	/**
	 * 获取用户租数
	 * 
	 * @return int 
	 */
	public function get_group_count(){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('group'));
		return $row['num'];
	}
	
	/**
	 * 搜索用户组成员
	 * @param int $group_id	用户组ID
	 * @param int $pagesize	页大小
	 * @param int $pagenum	页号
	 * 
	 * @return 二维数组（user结构）
	 */
	public function get_group_member_by_group_id($group_id,$pagesize,$pagenum){
		$q = "SELECT count(*) as num FROM ".DB::table('user_group')." as ug, "
		.DB::table('user')." as u where ug.group_id = $group_id and ug.user_id = u.user_id";
		$row = DB::fetchOne($q);
		
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		
		$q = "SELECT u.* as num FROM ".DB::table('user_group')." as ug, "
		.DB::table('user')." as u where ug.group_id = $group_id and ug.user_id = u.user_id"
		." limit $limitstart,$pagesize";
		$r = DB::fetchArray($q);
		return $r;
	}
	
	 /**
	  * 获取用户组成员数
	  * @param int $group_id 用户组ID
	  * 
	  * @return int 
	  */
	public function get_group_member_count_by_group_id($group_id){
		$q = "SELECT count(*) as num FROM ".DB::table('user_group')." as ug, "
		.DB::table('user')." as u where ug.group_id = $group_id and ug.user_id = u.user_id";
		$row = DB::fetchOne($q);
		return $row['num'];
	}
	
	/*********************************************待实现方法*********************************************/
	/**用户组权限修改*/
}
?>